package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        String contextPath = request.getContextPath();
        //判断请求是否是请求静态资源，如果是，标记为true，然后放行
        boolean flag = request.getRequestURI().endsWith("css") || request.getRequestURI().endsWith("jpg") || request.getRequestURI().endsWith("gif") || request.getRequestURI().endsWith("png");
        //当请求后缀是login.jsp或者login，或着session中user为空时，放行，进行登录，否则重定向到登陆页面
        if (flag || (request.getRequestURI().endsWith("login.jsp")) || (request.getRequestURI().endsWith("login")) || session.getAttribute("user") != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            response.sendRedirect(contextPath + "/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
